package com.pickgliss.keyboard
{
	import com.pickgliss.toplevel.StageReferance;
	
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.utils.Dictionary;
	
	[Event(name="keyDown",type="flash.events.KeyboardEvent")]
	[Event(name="keyUp",type="flash.events.KeyboardEvent")]
	public final class KeyboardManager extends EventDispatcher
	{
		public function KeyboardManager()
		{
			
		}
		
		public function setup():void
		{
			_keymap = new Dictionary();
			StageReferance.stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown,true,int.MAX_VALUE);
			StageReferance.stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp,true,int.MAX_VALUE);
		}
		
		private static var _instance:KeyboardManager;
		
		private var _keymap:Dictionary;
		public static function get Instance():KeyboardManager
		{
			if(_instance == null)
			{
				_instance = new KeyboardManager();
			}
			return _instance;
		}
		
		private function onKeyDown(event:KeyboardEvent):void
		{
			_keymap[event.keyCode] = true;
			dispatchEvent(event.clone());
		}
		
		private function onKeyUp(event:KeyboardEvent):void
		{
			delete _keymap[event.keyCode];
			dispatchEvent(event.clone());
		}
		
		public function keyIsDown(keyCode:int):Boolean
		{
			if(_keymap[keyCode] == null) return false;
			return _keymap[keyCode];
		}
	}
}